package com.act;

import java.util.ArrayList;

import org.apache.http.Header;
import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bean.Topic;
import com.bean.TopicList;
import com.common.Constant;
import com.common.LocalFileHelper;
import com.common.TextHttpResponseHandler;
import com.xike.kyt.R;
import com.xike.util.MyUtil;

public class TopicListAct extends BaseAct implements OnClickListener {
	TextView tv_back, tv_ok;
	ExpandableListView epListView;
	MyAdapter adapter;

	TopicList topicList;
	ArrayList<Topic> topics = new ArrayList<Topic>();
	String choseToplicIdStrs;
	ArrayList<Long> choseIds = new ArrayList<Long>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_topic_list);
		initViews();
		serviceGetTopics();
	}

	@Override
	protected void initViews() {
		tv_back = (TextView) findViewById(R.id.headTitle_tv_back);
		tv_ok = (TextView) findViewById(R.id.topicList_tv_ok);

		tv_back.setOnClickListener(this);
		tv_ok.setOnClickListener(this);

		epListView = (ExpandableListView) findViewById(R.id.topicList_epListView);
		epListView.setGroupIndicator(null);
		adapter = new MyAdapter();
		epListView.setAdapter(adapter);
	}

	@Override
	protected void updateViews() {
		ArrayList<Topic> resultTopics = topicList.getTopics();
		if (resultTopics == null || resultTopics.size() == 0) {
			mToast.showToast(this, "暂无话题");
		} else {
			topics.addAll(resultTopics);
			adapter.notifyDataSetChanged();
			for (int i = 0; i < adapter.getGroupCount(); i++) {
				epListView.expandGroup(i);
			}
			epListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

				@Override
				public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
					Long topicId = (Long) (adapter.getChildId(groupPosition, childPosition));
					if (choseIds.contains(topicId)) {
						choseIds.remove(topicId);
					} else {
						if (!choseIds.contains(topicId)) {
							choseIds.add(topicId);
						}
					}
					adapter.notifyDataSetChanged();
					return false;
				}
			});
			epListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {

				@Override
				public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
					Long topicId = (Long) (adapter.getGroupId(groupPosition));
					if (choseIds.contains(topicId)) {
						choseIds.remove(topicId);
						for (Topic t : topics.get(groupPosition).getChildTopic()) {
							Long childId = t.getId();
							choseIds.remove(childId);
						}
					} else {
						choseIds.add(topicId);
						for (Topic t : topics.get(groupPosition).getChildTopic()) {
							Long childId = t.getId();
							if (!choseIds.contains(childId)) {
								choseIds.add(childId);
							}
						}
					}
					adapter.notifyDataSetChanged();
					return true;
				}
			});
		}
	}

	private void serviceGetTopics() {

		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		// params.add(new BasicNameValuePair("question_id", String.valueOf(questionId)));
		// params.add(new BasicNameValuePair("content", strContent));

		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_TOPICS, params);
		// 本地缓存
		if (LocalFileHelper.getInstance(this).fileIsExited(strUrl)) {
			TopicList result = gson.fromJson(LocalFileHelper.getContentFromFile(strUrl), TopicList.class);
			dealRequestResult(result);
			return;
		}

		client.get(this, strUrl, new TextHttpResponseHandler(this) {

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
				mToast.showToast(TopicListAct.this, getString(R.string.net_error));
			}

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				super.onSuccess(statusCode, headers, responseString);
				TopicList result = gson.fromJson(responseString, TopicList.class);
				dealRequestResult(result);
			}

		});
	}

	private void dealRequestResult(TopicList result) {
		if (result == null) {
			mToast.showToast(TopicListAct.this, getString(R.string.net_error));
		} else {
			if (result.isReturnTrue()) {
				topicList = result;
				updateViews();
			} else {
				mToast.showToast(TopicListAct.this, result.getError_description());
			}
		}
	}

	class MyAdapter extends BaseExpandableListAdapter {
		private class ViewHolder {
			TextView tv_title, tv_description;
			ImageView img_image, img_chose;
		}

		ViewHolder parentHolder, childHolder;

		@Override
		public int getGroupCount() {
			return topics.size();
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return topics.get(groupPosition).getChildTopic().size();
		}

		@Override
		public Topic getGroup(int groupPosition) {
			return topics.get(groupPosition);
		}

		@Override
		public Topic getChild(int groupPosition, int childPosition) {
			return topics.get(groupPosition).getChildTopic().get(childPosition);
		}

		@Override
		public long getGroupId(int groupPosition) {
			return getGroup(groupPosition).getId();
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return getChild(groupPosition, childPosition).getId();
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = View.inflate(TopicListAct.this, R.layout.listitem_topic_parent, null);
				parentHolder = new ViewHolder();
				parentHolder.img_image = (ImageView) convertView.findViewById(R.id.lvItem_topicParent_img_image);
				parentHolder.img_chose = (ImageView) convertView.findViewById(R.id.lvItem_topicParent_img_chose);
				parentHolder.tv_title = (TextView) convertView.findViewById(R.id.lvItem_topicParent_tv_title);
				parentHolder.tv_description = (TextView) convertView.findViewById(R.id.lvItem_topicParent_tv_description);
				convertView.setTag(parentHolder);
			} else {
				parentHolder = (ViewHolder) convertView.getTag();
			}
			Topic topic = getGroup(groupPosition);
			Long id = topic.getId();
			if (choseIds.contains(id)) {
				parentHolder.img_chose.setSelected(true);
			} else {
				parentHolder.img_chose.setSelected(false);
			}
			BitmapDrawable defualtdrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.default_topic);
			Bitmap defaultBitmap = MyUtil.getRoundedCornerBitmap(defualtdrawable.getBitmap());
			MyUtil.displayImageView(TopicListAct.this, topic.getImage(), parentHolder.img_image, defaultBitmap, true);

			MyUtil.setTextViewText(parentHolder.tv_title, topic.getTitle(), View.INVISIBLE, "");
			MyUtil.setTextViewText(parentHolder.tv_description, topic.getDescription(), View.GONE, "");

			return convertView;
		}

		@Override
		public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = View.inflate(TopicListAct.this, R.layout.listitem_topic_child, null);
				childHolder = new ViewHolder();
				childHolder.img_chose = (ImageView) convertView.findViewById(R.id.lvItem_topicChild_img_chose);
				childHolder.tv_title = (TextView) convertView.findViewById(R.id.lvItem_topicChild_tv_title);
				childHolder.tv_description = (TextView) convertView.findViewById(R.id.lvItem_topicChild_tv_description);
				convertView.setTag(childHolder);
			} else {
				childHolder = (ViewHolder) convertView.getTag();
			}
			Topic topic = getChild(groupPosition, childPosition);
			Long id = topic.getId();
			if (choseIds.contains(id)) {
				childHolder.img_chose.setSelected(true);
			} else {
				childHolder.img_chose.setSelected(false);
			}

			MyUtil.setTextViewText(childHolder.tv_title, topic.getTitle(), View.INVISIBLE, "");
			MyUtil.setTextViewText(childHolder.tv_description, topic.getDescription(), View.GONE, "");

			return convertView;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return true;
		}

		@Override
		public boolean hasStableIds() {
			return false;
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.headTitle_tv_back:
			finish();
			break;
		case R.id.topicList_tv_ok:
			if (choseIds.size() > 0) {
				StringBuffer sb = new StringBuffer();
				for (Long id : choseIds) {
					sb.append(id).append(",");
				}
				String strToplicIds = sb.substring(0, sb.length() - 1).toString();
				Intent it = getIntent();
				it.putExtra("toplicIdStrs", strToplicIds);
				setResult(1, it);
			}
			finish();
			break;
		default:
			break;
		}
	}

}
